package com.aynu.admin.filter;

import cn.hutool.core.util.StrUtil;
import com.aynu.admin.utils.admin.JWTTool;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    private static final ThreadLocal<String> userPrincipal =new ThreadLocal<>();
    @Resource
    private JWTTool jwtTool;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println(request.getRequestURL());

        String authorization = request.getHeader("Authorization");
        if(StrUtil.isEmpty(authorization)||!authorization.startsWith("Bearer ")){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Access Denied: Invalid or missing token");
            return false; // 中断请求
        }
        String token = authorization.substring("Bearer ".length());
        if(jwtTool.isValid(token)){
            userPrincipal.set(jwtTool.getPayload(token,"user"));
            return true;
        }
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("Access Denied: Invalid or missing token");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        userPrincipal.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        userPrincipal.remove();
    }

    public static String getUserPrincipal(){
        return userPrincipal.get();
    }
}
